<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="css/table.css">
</head>
<body>
  <div>
    <table border="1px" align=center cellspacing="0" cellpadding="0">
      <caption>商品清单</caption>
      <thead>
        <tr>
          <th><input type="checkbox" name="" id="cbAll"></th>
          <th>商品</th>
          <th>价格</th>
        </tr>
      </thead>
      <tbody id="stb">
        <tr>
          <td><input type="checkbox" name="" id="cb1"></td>
          <td>iphone8</td>
         <td>8000</td>
        </tr>
        <tr>
          <td><input type="checkbox" name="" id="cb2"></td>
          <td>ipad pro</td>
          <td>5000</td>
        </tr>
        <tr>
          <td><input type="checkbox" name="" id="cb3"></td>
          <td>ipad air</td>
          <td>2000</td>
        </tr>
        <tr>
          <td><input type="checkbox" name="" id="cb4"></td>
          <td>apple watch</td>
          <td>1000</td>
        </tr>
      </tbody>
      
        
    </table>
    <input type="button" value="反选" id="btn">
  </div>
  <script>
    
//  -----------------------------------------------------  
    
    var cbAll = document.getElementById('cbAll');
    cbAll.onclick = function () { 
      var checkboxs = document.querySelectorAll('#stb input[type=checkbox]');
      var i = 0, len = checkboxs.length;
      // 测试
      // console.log(checkboxs); 
     for (i=0; i < len; i++){
      
      var checkbox = checkboxs[i];
      checkbox.checked = this.checked; 
     }  
    }
// ---------------------------------------------------
   var checkboxs = document.querySelectorAll('#stb input[type=checkbox]');
   var i = 0, len = checkboxs.length;
    for (i=0; i < len; i++ ) {
      var checkbox = checkboxs[i];
      checkbox.onclick = function () {
    // 引用函数
     fschecked();
      }
    }
//  --------------------------------------------------- 
 var btn = document.getElementById('btn');
 btn.onclick = function () {
   
   for (i=0 ; i < len; i++) {
     var checkbox = checkboxs[i]; 
     checkbox.checked = !checkbox.checked;
  
   }
  //  引用函数
   fschecked(); 
   }
  //构造一个函数实现子全选则父选，其他情况父都不选
  function fschecked() {
      var isAllChecked = true;
    for (i = 0; i < len; i++) {
      checkbox = checkboxs[i];
      if (!checkbox.checked) {
        isAllChecked = false;
        break;
      }
    }
    cbAll.checked = isAllChecked; 
  }
 
  

  </script>
</body>

</html>